import { defineStore } from 'pinia'
import { ref } from 'vue'
import pinia from '..'
import router from "@/router";
import { userLogin ,getStudentInfo} from "@/api/user/index";
import {reqLoginForm} from "@/api/user/type";
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import {TeacherItem, TeacherLoginForm} from "@/api/teacher/type";
import {getTeacherInfo, teacherLogin} from "@/api/teacher";
import {reqLoginForm} from "@/api/user/type";
import { GET_TEACHER,SET_TEACHER } from "@/utils/teacherInfo";
import {ElMessage} from "element-plus";
//创建用户小仓库
const useTeacherStore = defineStore('Teacher',() => {
    const token =ref<string>(GET_TOKEN() as string)

    const teacherInfo = ref<TeacherItem>({
        id: 0,
        username: '',
        password: '',
        name: '',
        email: '',
        phone: ''
    })

    async function login (loginForm: reqLoginForm) {
        try {
            const resLogin = await teacherLogin(loginForm)
            if (resLogin.code == 200) {
                SET_TOKEN(resLogin.data.token)
                console.log('老师存储token:',token.value)
                const resInfo = await getTeacherInfo()
                teacherInfo.value = resInfo.data
                SET_TEACHER(teacherInfo.value)
                console.log(teacherInfo.value)
                 router.push('/layout-teacher')
            }
            else {
                ElMessage.error(resLogin.message)
            }

        } catch (error) {
            await Promise.reject(error)
        }
    }

    return {
        token,
        teacherInfo,
        login
    }
})
//对外暴露获取小仓库方法
export default useTeacherStore

// 非setup
export function useTeacherStoreHook() {
    return useTeacherStore(pinia)
}
